package com.jinlejia.erp.ui.common;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.databinding.ActivityInfoVerificationBinding;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DbUtil;
import com.jinlejia.erp.utils.SharePTool;
import com.lab.Lab;
import com.lab.user.LabLogonCallBack;
import com.utils.MD5Utils;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 短信验证（Activity）
 */

public class VerificationActivity extends AppCompatActivity {
    private String tel;

    private CountDownTimer cdt;
    ProgressDialog progressDialog;

    private ActivityInfoVerificationBinding binding;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_info_verification);
        binding.setEvent(this);
        Intent intent = getIntent();
        tel = intent.getStringExtra("tel");
        initView();
        Resend();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        progressDialog = new ProgressDialog(this, "请稍后...");
        binding.telNumber.setText("短信验证码已发送至" + tel);

        binding.verifyNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                checkEdit();
            }
        });

        cdt = new CountDownTimer(90 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                binding.resend.setClickable(false);
                binding.resend.setText("重新发送（" + millisUntilFinished / 1000 + "）");
            }

            @Override
            public void onFinish() {
                binding.resend.setClickable(true);
                binding.resend.setText("重新发送");
            }
        }.start();
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn://返回
                finish();
                break;
            case R.id.resend://重新发送
                Resend();
                cdt.start();
                break;
            case R.id.close:   //清除
                binding.verifyNumber.setText("");
                checkEdit();
                break;
            case R.id.commit:  //确定
                progressDialog.show();
                if (TextUtils.isEmpty(binding.verifyNumber.getText().toString())) {
                    if (null != progressDialog && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    CustomToast.showToast(this, "验证码不能为空", 2000);
                } else {
                    Commit();
                }
                break;
        }
    }

    private void checkEdit() {
        if (!TextUtils.isEmpty(binding.verifyNumber.getText().toString())) {
            binding.close.setVisibility(View.VISIBLE);
        } else {
            binding.close.setVisibility(View.GONE);
        }
    }

    /**
     * 重新发送验证码
     */
    public void Resend() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pin", getIntent().getStringExtra("pin"));
            jsonObject.put("password", MD5Utils.md5(getIntent().getStringExtra("password")));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils
                .postString()
                .url(ApiConfig.CAPTCHA)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(VerificationActivity.this, response, null)) {
                            CustomToast.showToast(VerificationActivity.this, "发送成功", 2000);
                        }
                    }
                });
    }

    /**
     * 提交验证码
     */
    public void Commit() {
        hideSoftKeyboard();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pin", getIntent().getStringExtra("pin"));
            jsonObject.put("password", MD5Utils.md5(getIntent().getStringExtra("password")));
            jsonObject.put("checkCode", binding.verifyNumber.getText());
            jsonObject.put("deviceCode", getIntent().getStringExtra("deviceCode"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils
                .postString()
                .url(ApiConfig.COMMIT_CAPTCHA)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomToast.showToast(VerificationActivity.this,"网络链接失败",1500);
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(final Map<String, Object> response, int id) {
                        if (DataFilter.filter(VerificationActivity.this, response, null)) {
                            final com.alibaba.fastjson.JSONObject object = JSON.parseObject(response.get("data").toString());
                            JPushInterface.resumePush(VerificationActivity.this);
                            final String pin = object.get("pin").toString();
                            final String cookie = object.getString("cookie");
                            loadUserInfo(pin,cookie);

                        } else {
                            if (null != progressDialog && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                        }
                    }
                });
    }

    private void loadUserInfo(final String pin,final String cookie){
        DbUtil.getDB(this).single().save(new SaveCookieBean(200, cookie));
        DbUtil.getDB(this).single().save(new SaveCookieBean(202, pin));
        OkHttpUtils
                .get()
                .url(ApiConfig.PERSONAL_INFO)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomToast.showToast(VerificationActivity.this,"网络链接失败",1500);
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if ("200".equals(String.valueOf(response.get("code")))){
                            com.alibaba.fastjson.JSONObject json= JSON.parseObject(String.valueOf(response.get("data")));
                            //region 保存用户信息
                            String imageUrl = String.valueOf(json.get("imageUrl"));
                            String userName =json.getString("name");
                            String telNum = json.getString("tel");
                            String titleLevel =json.getString("titleLevel");
                            String email = json.getString("email");
                            String deptName = json.getString("deptName");
                            String shareStoreName = json.getString("shareStoreName");;

                            SharePTool.UserInfoBean bean = new SharePTool.UserInfoBean();
                            bean.setCookie(cookie);
                            bean.setPin(pin);
                            bean.setImageUrl(imageUrl);
                            bean.setEmail(email);
                            bean.setTelNum(telNum);
                            bean.setTitleLevel(titleLevel);
                            bean.setDeptName(deptName);
                            bean.setUserName(userName);
                            bean.setShareStoreName(shareStoreName);

                            SharePTool.saveUserInfoBean(VerificationActivity.this,bean);
                            //endregion

                            Lab.userLifecycle().onLogon(VerificationActivity.this, bean, new LabLogonCallBack() {
                                @Override
                                public void loginSuccess() {
                                    if (null != progressDialog && progressDialog.isShowing()) {
                                        progressDialog.dismiss();
                                    }
                                    Intent intent = new Intent(VerificationActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }

                                @Override
                                public void loginFailed(@NotNull String msg) {
                                    if (null != progressDialog && progressDialog.isShowing()) {
                                        progressDialog.dismiss();
                                    }
                                    CustomToast.showToast(VerificationActivity.this,msg,1500);
                                }
                            });
                        }else {
                            String message = String.valueOf(response.get("message"));
                            if (!TextUtils.isEmpty(message) && !"null".equalsIgnoreCase(message)){
                                CustomToast.showToast(VerificationActivity.this,message,1500);
                            }else {
                                CustomToast.showToast(VerificationActivity.this,"与服务器链接失败",1500);
                            }
                            if (null != progressDialog && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                        }
                    }
                });
    }

    protected void hideSoftKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                    0);
        }
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
